import React, { useEffect, useState } from "react";
import { Card, Form, Button, Input, Select, Table, message } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

import { initHospitalListRequest, getProvinceRequest, getCityOrDistrictRequest, hospitalListStatusRuquest } from "@/api/hospital/hodpitalListRequest";

import type {
  hosListParamsType,
  hosListReturnContentType,
  hosListReturnItemType,
  getProvinceReturnType
} from "@api/hospital/model/hospitalListType";

export default function HospitalList() {
  //编程式路由跳转
  const navigate = useNavigate()


  //定义表单实例
  const [form] = Form.useForm()
  //定义加载动画状态
  const [isLoading, setIsLoading] = useState(false);
  //定义重新加载页面State
  const [reload, setReload] = useState(true)
  //定义页码请求结果状态
  const [result, setResult] = useState<hosListReturnContentType>([]);
  //定义当前页码状态
  const [page, setPage] = useState(1);
  //定义每页条数状态
  const [limit, setLimit] = useState(3);
  //定义数据总数
  const [totalElements, setTotalElements] = useState(0);
  //定义查询参数
  const [searchParams, setSearchParams] = useState<hosListParamsType>({});
  //定义三级联动之省份
  const [province, setProvince] = useState<getProvinceReturnType>([])
  //定义三级联动之市或区
  const [cityList, setCityList] = useState<getProvinceReturnType>([])
  //定义三级联动之县
  const [district, setDistrict] = useState<getProvinceReturnType>([])
  //定义医院类型
  const [hosType, sethosType] = useState<getProvinceReturnType>([])

  //1.初始分页请求
  useEffect(() => {
    setIsLoading(true);
    const initList = async () => {
      const result = await initHospitalListRequest(
        { page, limit },
        searchParams
      );
      //控制加载动画
      setIsLoading(false);
      //设置列表数据
      setResult(result.content);
      //设置数据总条数
      setTotalElements(result.totalElements);
    };
    initList();
  }, [searchParams, page, limit, reload]);


  //2.初始获取省份
  useEffect(() => {
    const getProvince = async () => {
      const result = await getProvinceRequest()
      //设置省份State
      setProvince(result)
    }
    getProvince();
  }, [])

  //初始获取医院类型
  useEffect(() => {
    const getHosType = async () => {
      const result = await getCityOrDistrictRequest("10000")
      sethosType(result)
    }
    getHosType()
  }, [])



  //选择省份获取市或区信息的回调
  const getcityListHandel = (value: string) => {
    const getCityList = async () => {
      const result = await getCityOrDistrictRequest(value)
      setCityList(result)
      //重新选择省份,清空表单中市的信息
      form.setFieldsValue({ cityCode: null, districtCode: null })
      //清空县级数据
      setDistrict([])
    }
    getCityList()
  }
  //选择市获取县级信息的回调
  const getDistrictHandle = (value: string) => {
    const getDistrict = async () => {
      const result = await getCityOrDistrictRequest(value)

      setDistrict(result)
      //重新选择市,清空表单中县的信息
      form.setFieldsValue({ districtCode: null })
    }
    getDistrict()
  }

  //点击查询收集表单数据并设置回调
  const searchHandel = (value: hosListParamsType) => {
    //把参数设置给查询参数的State
    setSearchParams(value)
  }

  //点击上下线更新状态的回调
  const hospitalListStatusHandle = (id: string, status: 0 | 1) => {

    return () => {
      const changeStatus = async () => {
        await hospitalListStatusRuquest(id, status)
        //设置重新加载状态
        setReload(!reload)
        //设置上下线操作全局提醒
        status ? message.success('上线成功') : message.success('下线成功')

      }
      changeStatus()
    }
  }

  

  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return (
          <img width={100} src={`data:/image/jpeg;base64,${logoData}`} alt="" />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: hosListReturnItemType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: hosListReturnItemType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: hosListReturnItemType) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      dataIndex: "id",
      render(_: any, data: hosListReturnItemType) {
        return (
          <div>
            <Button type="primary" onClick={() => { navigate(`/syt/hospital/hospitalShow/${data.id}`) }}>查看</Button>
            <Button type="primary" onClick={()=>{navigate(`/syt/hospital/hospitalSchedule/${data.hoscode}`)}}>排班</Button>
            <Button type="primary"
              onClick={hospitalListStatusHandle(data.id, data.status === 0 ? 1 : 0)}>
              {data.status === 0 ? '上线' : '下线'}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          // wrapperCol={{ span: 30 }}
          layout="inline"
          form={form}
          onFinish={searchHandel}
        >
          <Form.Item name="provinceCode" style={{ width: 200 }}>
            <Select placeholder="请输入省份" allowClear onChange={getcityListHandel}>

              {
                province.map(item => {
                  return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                })
              }

            </Select>
          </Form.Item>
          <Form.Item name="cityCode" style={{ width: 200 }}>
            <Select placeholder="请输入市" allowClear onChange={getDistrictHandle}>

              {
                cityList.map(item => {
                  return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                })
              }

            </Select>
          </Form.Item>
          <Form.Item name="districtCode" style={{ width: 200 }}>
            <Select placeholder="请输入县/区" allowClear>
              {
                district.map(item => {
                  return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="hosname" style={{ width: 200 }}>
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode" style={{ width: 200, marginTop: "20px" }}>
            <Input placeholder="医院编号" />
          </Form.Item>
          <Form.Item name="hostype" style={{ width: 200, marginTop: "20px" }}>
            <Select placeholder="医院类型" allowClear>
              {
                hosType.map(item => {
                  return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="status" style={{ width: 200, marginTop: "20px" }}>
            <Select placeholder="医院状态" allowClear>
              <Select.Option value={1}>上线</Select.Option>
              <Select.Option value={0}>下线</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginTop: "20px" }}
              icon={<SearchOutlined />}
            >
              查询
            </Button>
          </Form.Item>
          <Form.Item
            wrapperCol={{ offset: 8, span: 16 }}
            style={{ marginTop: "20px" }}
          >
            <Button type="default" htmlType="reset" onClick={() => { setSearchParams({}) }}>
              清空
            </Button>
          </Form.Item>
        </Form>

        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={result}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total: totalElements,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange: (page: number, pageSize: number) => {
              //设置页码State
              setPage(page)
              setLimit(pageSize)
            }
          }}
        />
      </Card>
    </div>
  );
}
